package com.lxm.ymcc.mq.lister;

import com.alibaba.fastjson.JSON;
import com.lxm.ymcc.constans.Mq;
import com.lxm.ymcc.domain.CourseOrder;
import com.lxm.ymcc.dto.MqOrder;
import com.lxm.ymcc.service.ICourseOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

@RocketMQTransactionListener(txProducerGroup = Mq.PRODUCE_GROUP)
public class MqOrderLister implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    /*
    msg  消息体
    arg   额外的数据
     */



    // 监听本地事物
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        if (arg!=null&&arg instanceof CourseOrder) {

            try {
                CourseOrder courseOrder = (CourseOrder) arg;
                // 保存数据
                courseOrderService.saveOnOrder(courseOrder);
                return RocketMQLocalTransactionState.COMMIT;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
    // 检查本地事物
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        byte[] bytes = (byte[]) message.getPayload();

        if(message == null || message.getPayload() == null ){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        try {
            // 转化数据-》string
            String string = new String(bytes);
            // 数据还原
            MqOrder mqOrder = JSON.parseObject(string, MqOrder.class);
            // 获取订单编号
            String orderNo = mqOrder.getOrderNo();
            // 根据订单编号查询订单
            CourseOrder courseOrder = courseOrderService.selectOneOrSn(orderNo);
            if (courseOrder!=null){
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
